#!/usr/bin/python3
# -*- coding: utf-8 -*-
# 使用 requests 库
import traceback

import requests
import json
import os
import logging

from loguru import logger

logger.add("/var/log/Task/netbox/Tasks.log", rotation="00:00", backtrace=True, diagnose=True, level="DEBUG")


# ------netbox_api get groupInfo----------
def netbox_get_group(netbox_url, netbox_token, limit, verify=None):
    response = requests.get(f'{netbox_url}/api/dcim/sites/?limit=' + limit,
                            headers={'Content-Type': 'application/json', 'accept': 'application/json',
                                     'Authorization': 'Token ' + netbox_token},
                            verify=verify)
    logger.info("拉取Netbox_group Info···")
    groupInfo = response.text
    # json.loads 将已编码的 JSON 字符串解码为 Python 对象
    groupInfoPython = json.loads(groupInfo)
    # 从字典里取 data 数组
    dataList = groupInfoPython.get('results')
    return dataList


# ------获取hosts---------------------------
def netbox_get_hosts(netbox_url, netbox_token, limit, offset, verify=None):
    response = requests.get(f'{netbox_url}/api/dcim/devices/?limit=' + limit + '&offset=' + offset,
                            headers={'Content-Type': 'application/json', 'accept': 'application/json',
                                     'Authorization': 'Token ' + netbox_token}, verify=verify)
    logger.info("拉取Netbox_host Info···")
    devicesInfo = response.text
    # json.loads 将已编码的 JSON 字符串解码为 Python 对象
    devicesInfoPython = json.loads(devicesInfo)
    # 从字典里取 data 数组
    # dataList = devicesInfoPython.get('results')
    return devicesInfoPython


# ---------获取IP段--------------------------
def netbox_get_prefix(netbox_url, netbox_token, limit, verify=None):
    response = requests.get(f'{netbox_url}/api/ipam/prefixes/?limit=' + limit,
                            headers={'Content-Type': 'application/json', 'accept': 'application/json',
                                     'Authorization': 'Token ' + netbox_token}, verify=verify)
    logger.info("拉取Netbox_prefix Info···")
    Info = response.text
    # json.loads 将已编码的 JSON 字符串解码为 Python 对象
    InfoPython = json.loads(Info)
    # 从字典里取 data 数组
    dataList = InfoPython.get('results')
    return dataList


# netbox创建 /ipam/prefixes/
def netbox_create_ipam(netbox_url, netbox_token, data, verify=None):
    data = json.dumps(data)
    response = requests.post(f'{netbox_url}/api/ipam/prefixes/',
                             headers={
                                 'Content-Type': 'application/json', 'accept': 'application/json',
                                 'Authorization': 'Token ' + netbox_token}, verify=verify,
                             data=data)
    create_info = response.text
    try:
        data = json.loads(create_info)
    except ValueError:
        print(str(create_info))
    return data

# netbox更新 /ipam/prefixes/
def netbox_update_ipam(netbox_url, netbox_token, data, netbox_id, verify=None):
    response = requests.put(f'{netbox_url}/api/ipam/prefixes/{netbox_id}/',
                            headers={'Content-Type': 'application/json', 'accept': 'application/json',
                                     'Authorization': 'Token ' + netbox_token}, verify=verify,
                            data=json.dumps(data))
    create_info = response.text
    try:
        data = json.loads(create_info)
    except ValueError:
        print(str(create_info))
    return data

# ---------获取IP信息--------------------------
def netbox_get_ip_addresses(netbox_url, netbox_token, limit, verify=None):
    response = requests.get(f'{netbox_url}/api/ipam/ip-addresses/?limit=' + limit,
                            headers={'Content-Type': 'application/json', 'accept': 'application/json',
                                     'Authorization': 'Token ' + netbox_token}, verify=verify)
    logger.info("拉取Netbox_ip-addresses Info···")
    Info = response.text
    # json.loads 将已编码的 JSON 字符串解码为 Python 对象
    InfoPython = json.loads(Info)
    # 从字典里取 data 数组
    dataList = InfoPython.get('results')
    return dataList


# ---------获取 circuite线路 全量信息-------------------------


def netbox_get_circuits(netbox_url, netbox_token, verify=None):
    response = requests.get(
        f'{netbox_url}/api/circuits/circuits/',
        headers={'Content-Type': 'application/json', 'accept': 'application/json',
                 'Authorization': 'Token ' + netbox_token}, verify=verify)
    logger.info("拉取Netbox_circuits Info···")
    circuitsInfo = response.text
    # json.loads 将已编码的 JSON 字符串解码为 dict 对象
    circuits_dict = json.loads(circuitsInfo)
    # 从字典里取 data 数组
    # dataList = circuitsPython.get('results')
    return circuits_dict


# ---------获取 Cables 信息--------------------------

# 2022年7月7日 马冲 修改过
def netbox_get_cables(netbox_url, netbox_token, verify=None):
    response = requests.get(f'{netbox_url}/api/dcim/cables/',
                            headers={'Content-Type': 'application/json', 'accept': 'application/json',
                                     'Authorization': 'Token ' + netbox_token}, verify=verify)
    resp = response.text
    resp_dict = json.loads(resp)
    return resp_dict


# ----------获取interfaces------------------------------
def netbox_get_interfaces(netbox_url, netbox_token, limit, verify=None):
    response = requests.get(f'{netbox_url}/api/dcim/interfaces/?limit=' + limit,
                            headers={'Content-Type': 'application/json', 'accept': 'application/json',
                                     'Authorization': 'Token ' + netbox_token}, verify=verify)
    logger.info("拉取Netbox_interface Info···")
    logger.info(netbox_token)
    logger.info(limit)
    logger.info(response)
    Info = response.text
    # json.loads 将已编码的 JSON 字符串解码为 Python 对象
    Python = json.loads(Info)
    # 从字典里取 data 数组
    dataList = Python.get('results')
    return dataList


# ------获取next---------------------------
def netbox_get_next(netbox_token, nexturl, verify=None):
    logger.info(nexturl)
    response = requests.get(nexturl, headers={'Content-Type': 'application/json', 'accept': 'application/json',
                                              'Authorization': 'Token ' + netbox_token}, verify=verify)
    nextInfo = response.text
    # logger.info(nextInfo)
    # json.loads 将已编码的 JSON 字符串解码为 Python 字典 对象
    try:
        data = json.loads(nextInfo)
    except ValueError:
        logger.info(str(nextInfo))
        logger.info(f"格式化错误，{traceback.format_exc()}")
        # logger.error(f"格式化错误，{nextInfo}")
    return data


def netbox_get_site(netbox_token, netbox_url, verify=None):
    response = requests.get(
        f'{netbox_url}/api/dcim/sites/',
        headers={'Content-Type': 'application/json', 'accept': 'application/json',
                 'Authorization': 'Token ' + netbox_token}, verify=verify)
    logger.info("拉取Netbox_circuits Info···")
    site_info = response.text
    # json.loads 将已编码的 JSON 字符串解码为 dict 对象
    site_dict = json.loads(site_info)
    # 从字典里取 data 数组
    return site_dict


def update_device(url, netbox_token, data, verify=None):
    headers = {'Content-Type': 'application/json',
               'accept': 'application/json',
               'Authorization': 'Token ' + netbox_token}
    response = requests.patch(url=url, headers=headers, data=json.dumps(data), verify=verify)
    device_info = json.loads(response.text)
    return device_info

# ip = "10.31.137.41"
# resp = netbox_get_next("0674da9880ad5d6c0eeb50e4595b964fdea51f7a",
#                        f"https://netbox.int.xiaohongshu.com/api/dcim/devices/?cf_ManagementIP={ip}", False)
# print(resp)
